# setup_git_filter.ps1
param(
    [string]$EnvFile = ".env",
    [switch]$Local = $false
)

function ThrowError($message)
{
    Write-Host "❌ 错误: $message" -ForegroundColor Red
    exit 1
}
# --- 主流程 ---
if (-not (Get-Command git -ErrorAction SilentlyContinue))
{
    ThrowError "Git 未安装！请先安装 Git。"
}
# 加载.env文件中的环境变量
$envVariables = @{ }
if (Test-Path $EnvFile)
{
    Get-Content $EnvFile | ForEach-Object {
        if ($_ -match '^\s*([^=#]+?)\s*=\s*(.*?)\s*(?:#.*)?$')
        {
            $name = $matches[1].Trim()
            $value = $matches[2].Trim()
            if ($value -match '^["''](.*)["'']$')
            {
                $value = $matches[1]
            }
            $envVariables[$name] = $value
        }
    }
}
else
{
    ThrowError "未找到环境变量文件 $EnvFile"
}

# --- 创建过滤器脚本目录 ---
$filterDir = ".git_filters"
New-Item -ItemType Directory -Path $filterDir -Force | Out-Null

# --- 生成 Clean 脚本 ---
$cleanLines = @"
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 从标准输入读取内容
`$content = `$input | Out-String

# 如果输入为空，直接返回
if ([string]::IsNullOrEmpty(`$content)) {
    Write-Output `$content
    exit
}
# 初始化替换规则哈希表
`$replaceRules = @{}

"@
$cleanBlock = @()
# 添加每个环境变量的替换规则
foreach ($varName in $envVariables.Keys)
{
    $cleanBlock += "`$escapedKey = [regex]::Escape('$varName')" + "`n"
    $cleanBlock += "`$replaceRules[`$escapedKey] = '{{$varName}}'" + "`n"
}
$cleanLines += $cleanBlock
$cleanBlock = @"
    foreach (`$key in `$replaceRules.Keys) {
        `$escapedKey = [regex]::Escape(`$key)
        `$pattern = "(``"?`$escapedKey``"?\s*:\s*[``"'`']?)(.*?)([``"'`']?\s*[,}])"
        `$content = `$content -replace `$pattern, "```${1}`$(`$replaceRules[`$key])```${3}"
    }

"@
$cleanLines += $cleanBlock
$cleanLines += "Write-Output `$content"

$cleanPath = Join-Path $filterDir "clean.ps1"
$cleanLines -join "`n" | Out-File $cleanPath -Encoding utf8

# --- 生成 Smudge 脚本 ---
$smudgeLines = @"
# 设置输入输出编码为 UTF-8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# 从标准输入读取内容
`$content = `$input | Out-String
# 如果输入为空，直接返回
if ([string]::IsNullOrEmpty(`$content)) {
    Write-Output `$content
    exit
}
`$replaceRules = @{

"@

# 添加每个环境变量的替换规则
foreach ($varName in $envVariables.Keys)
{
    $smudgeLines += "    [regex]::Escape('{{$varName}}') = `$env:$varName" + "`n"
}

$smudgeLines += "}"
$smudgeLines = @"
    $smudgeLines
    foreach (`$placeholder in `$replaceRules.Keys) {
        `$value = `$replaceRules[`$placeholder]
        if ([string]::IsNullOrEmpty(`$value)) {
            Write-Warning "占位符 '`$placeholder' 对应的环境变量未设置"
            continue
        }
        `$content = `$content -replace `$placeholder, `$value
    }

   Write-Output `$content

"@

$smudgePath = Join-Path $filterDir "smudge.ps1"
$smudgeLines -join "`n" | Out-File $smudgePath -Encoding utf8

# --- 更新 .gitattributes ---
$filePatterns = @("*.yaml", "*.json", "*.yml", "*.env")
foreach ($pattern in $filePatterns)
{
    $existingRule = Get-Content .gitattributes -ErrorAction SilentlyContinue |
            Where-Object { $_ -match "^$([regex]::Escape($pattern) )\s+" }
    if (-not $existingRule)
    {
        Add-Content .gitattributes "$pattern filter=secrets" -Encoding utf8
    }
}

# --- 注册 Git 过滤器 ---
$gitConfigScope = if ($Local)
{
    "--local"
}
else
{
    "--global"
}
$cleanCommand = "pwsh -File `"$( (Resolve-Path $cleanPath).Path )`""
$smudgeCommand = "pwsh -File `"$( (Resolve-Path $smudgePath).Path )`""

git config $gitConfigScope filter.secrets.clean "$cleanCommand"
git config $gitConfigScope filter.secrets.smudge "$smudgeCommand"

Write-Host @"
✅ Git自动化配置已完成！

下一步操作：
1. 测试替换效果：
   git add .
   git commit -m '测试过滤器'
   git show HEAD  # 查看占位符
   git checkout HEAD -- .  # 恢复真实值
2. 使用Git插件进行上传代码

团队协作需同步配置：
1. 创建.env文件并填写环境变量
2. 运行此脚本完成配置
"@ -ForegroundColor Green